package org.lzy.shop.activity

import android.graphics.BitmapFactory
import android.text.TextUtils
import android.util.Base64
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import androidx.core.graphics.toColorInt
import com.google.android.material.textview.MaterialTextView
import com.kongzue.dialogx.dialogs.BottomDialog
import com.kongzue.dialogx.interfaces.OnBindView
import org.lzy.shop.Constant
import org.lzy.shop.R
import org.lzy.shop.base.BaseMvvmActivity
import org.lzy.shop.databinding.ActivityLoginBinding
import org.lzy.shop.util.BitmapUtils.calculateInSampleSize
import org.lzy.shop.util.DataStoreUtils
import org.lzy.shop.viewmodel.LoginViewModel

/**
 * 登录
 */

class LoginActivity: BaseMvvmActivity<ActivityLoginBinding, LoginViewModel>({ ActivityLoginBinding.inflate(it) }) {

    override fun initView() {

    }

    override fun requestData() {

    }

    //后台返回成功全部在initData完成，initView只做初始化
    override fun initData() {
                //登录成功后
                mViewModel.loginLiveData.observeWithLifecycle(this@LoginActivity){ loginResponse->
                    dismissLoading()
                    loginResponse?.let {
                        // 保存token
                        DataStoreUtils.putToken(Constant.TOKEN, loginResponse.token)
                        DataStoreUtils.putToken(Constant.REFRESHTOKEN, loginResponse.refreshToken)
                        finish()
                    }

                }

                //图片验证码成功回调
                mViewModel.picSmsLiveData.observeWithLifecycle(this@LoginActivity){picSmsResponse ->
                    dismissLoading()
                    picSmsResponse?.let {
                        //显示图形返回base64，要把开头data:image/png;base64给抹掉否则显示不出
                        BottomDialog.show(object : OnBindView<BottomDialog?>(R.layout.picsmsbottomdialog) {
                            override fun onBind(dialog: BottomDialog?, view: View) {
                                val editCode = view.findViewById<EditText>(R.id.pic_sms_num)
                                val img = view.findViewById<ImageView>(R.id.pic_sms_show)
                                // Base64解码
                                val decodedBytes = Base64.decode(picSmsResponse.data.replace("data:image/png;base64", ""), Base64.DEFAULT)
                                val options = BitmapFactory.Options()
                                // 设置适当的采样率
                                options.inSampleSize = calculateInSampleSize(options, 200, 100) // 根据实际UI大小调整
                                // 创建Bitmap
                                val decodedBitmap = BitmapFactory.decodeByteArray(decodedBytes, 0, decodedBytes.size,options)
                                img.setImageBitmap(decodedBitmap)
                                val sureBtn = view.findViewById<MaterialTextView>(R.id.btnSure)
                                sureBtn.setOnClickListener {
                                    if (TextUtils.isEmpty(editCode.text.toString())) {
                                        showToast(getResString(R.string.pic_sms_hint))
                                    } else {
                                        dialog?.dismiss()
                                        mViewModel.sendSms(binding.actLoginNewEtAccount.text.toString(), picSmsResponse.captchaId!!, editCode.text.toString()
                                        )
                                    }
                                }
                            }
                        }).setAllowInterceptTouch(false).setMaskColor("#4D000000".toColorInt())
                    }
                }

                //图片验证后再次发送验证码
                mViewModel.smsLiveData.observeWithLifecycle(this@LoginActivity){smsResponse ->
                    dismissLoading()
                    smsResponse?.let {
                        binding.actLoginNewEtPsw.setText(smsResponse)
                    }
                }
    }

    override fun allClick() {
        //注册
        binding.loginNewTvRegister.setOnClickListener {
            startActivity(RegisterActivity::class.java)
        }

        //忘记密码
        binding.loginNewTvForgetpwd.setOnClickListener {
            startActivity(ForgetPwdActivity::class.java)
        }

         //登录
        binding.actLoginNewBtnLogin.setOnClickListener {
            val username = binding.actLoginNewEtAccount.text.toString()
            val password = binding.actLoginNewEtPsw.text.toString()
            if (TextUtils.isEmpty(username)) {
                showToast(getResString(R.string.input_mobile))
            } else if (TextUtils.isEmpty(password)) {
                showToast(getResString(R.string.input_code))
            } else if (!binding.cb.isChecked) {
                showToast(getResString(R.string.please_caluse))
            } else {
                // 显示加载框
                showLoading()
                // 发起登录
                mViewModel.loginSms(username, password)

            }

        }
        //发送验证码
        binding.countdown.setOnClickListener {
            val username = binding.actLoginNewEtAccount.text.toString()
            if (TextUtils.isEmpty(username)) {
                showToast(getResString(R.string.input_mobile))
            }else{
                sendSmsMessage()
            }

        }

    }


    //发送验证码
    fun sendSmsMessage(){
        val userMobile = binding.actLoginNewEtAccount.text.toString()
        if (TextUtils.isEmpty(userMobile)) {
            showToast(getString(R.string.mobile_empty))
            return
        }
        if (userMobile.length < Constant.ELEVEN) {
            showToast(getResString(R.string.mobile_error))
            return
        }

        if (binding.countdown.getmCurrentmillis() > Constant.TWOTHOURSANDS) {
            showToast((binding.countdown.getmCurrentmillis() / 1000).toString() + getResString(R.string.try_again_in_seconds))
            return
        }
        showLoading()
        mViewModel.getPicSms()
    }



}